package com.hqyj.erpserver.util;

import com.hqyj.erpserver.dao.entity.SysUser;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JWTUtil {
    @Value("${jwt.token.secret}")  //从配置文件application.properties中获取配置项的值
    private String AUTHORIZE_TOKEN_SECRET;
    @Value("${jwt.token.expire}")
    private long AUTHORIZE_TOKEN_EXPIRE;

    public String createJwt(SysUser sysUser) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        Map<String, Object> map = new HashMap<>();
        map.put("role", sysUser.getUserRole());
        map.put("id", "" + sysUser.getUserId());
        //map.put("userPwd", user.getUserPwd());
        JwtBuilder builder = Jwts.builder()
                .setClaims(map)  //设置附加信息
                // .setId("1")
//                .setSubject("权限验证")   // 主题
                .setIssuer("com.hqyj")     // 签发者
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, AUTHORIZE_TOKEN_SECRET); // 签名算法以及密匙
        long expMillis = nowMillis + AUTHORIZE_TOKEN_EXPIRE*1000;
        Date expDate = new Date(expMillis);
        builder.setExpiration(expDate); // 过期时间
        return builder.compact();
    }
    /**
     * 验证JWT
     * @param jwtStr
     * @return
     */

    public RestResult<Claims> validateJWT(String jwtStr) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(AUTHORIZE_TOKEN_SECRET)
                    .parseClaimsJws(jwtStr)
                    .getBody();
            return RestResult.ok(claims,"校验成功");
        } catch (ExpiredJwtException e) {
            return RestResult.error(2, "token过期");
        } catch (SignatureException e) {
            return RestResult.error(3,"token校验异常");
        } catch (Exception e) {
            return RestResult.error(4,"token异常");
        }
    }
}
